package dswork.common.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import dswork.common.model.IUser;
import dswork.common.model.IUserBm;
import dswork.core.db.MyBatisDao;
import dswork.core.util.IdUtil;
import dswork.core.util.TimeUtil;

@Repository
@SuppressWarnings("all")
public class DsBaseUserDao extends MyBatisDao
{
	private SqlSessionTemplate sqlSessionTemplateCommon;
	private static boolean hasCommon = false;

	@Override
	protected SqlSessionTemplate getSqlSessionTemplate()
	{
		if(hasCommon)
		{
			return sqlSessionTemplateCommon;
		}
		return super.getSqlSessionTemplate();
	}
	
	public void setSqlSessionTemplateCommon(SqlSessionTemplate sqlSessionTemplate)
	{
		if(log.isInfoEnabled())
		{
			log.info("======== DsCommonDaoCommonIDict call setSqlSessionTemplateCommon ========");
		}
		hasCommon = true;
		this.sqlSessionTemplateCommon = sqlSessionTemplate;
	}
	
	@Override
	public Class getEntityClass()
	{
		return DsBaseUserDao.class;
	}

	public int saveUserBm(IUserBm bm)
	{
		return executeInsert("insertUserBm", bm);
	}
	
	public int deleteUser(long id)
	{
		return executeDelete("deleteUser", id);
	}

	public int updateUserid(IUser user, String oldBm, String newBm)
	{
		if(user != null && oldBm != null && newBm != null)
		{
			newBm = newBm.toLowerCase(Locale.ENGLISH);
			IUserBm bm = getUserBm(newBm);
			if(bm == null)
			{
				bm = new IUserBm();
				bm.setBm(newBm);
				bm.setUserid(user.getId());
				bm.setType(1);
				executeInsert("insertUserBm", bm);
			}
			else
			{
				bm.setUserid(user.getId());
				bm.setType(1);
				executeUpdate("updateUserBm", bm);
			}
			oldBm = oldBm.toLowerCase(Locale.ENGLISH);
			if(!oldBm.equals(newBm))
			{
				IUser u = new IUser();
				u.setId(user.getId());
				u.setMobile(newBm);
				executeUpdate("updateUserMobile", u);
			}
			
			IUserBm o = getUserBm(oldBm);// bm的userid有可能为空或不是自己
			if(user.getId() == o.getUserid())
			{
				if(oldBm.equals(newBm))
				{
					
				}
				else
				{
					o.setUserid(0);
					executeUpdate("updateUserBm", o);
				}
			}
			
			return 1;
		}
		return 0;
	}

	public IUserBm getUserBm(String bm)
	{
		return (IUserBm) executeSelect("getUserBm", bm);
	}

	public int saveUser(IUser user, List<String> bmList)
	{
		if(bmList == null)
		{
			bmList = new java.util.ArrayList<String>();
		}
		user.setAccount(user.getAccount().trim().toLowerCase(Locale.ENGLISH));// 数据库本质使用小写
		user.setPassword(user.getPassword().trim().toUpperCase(Locale.ENGLISH));
		user.setMobile(user.getMobile().trim().toLowerCase(Locale.ENGLISH));
		user.setIdcard(user.getIdcard().trim().toUpperCase(Locale.ENGLISH));
		user.setCreatetime(TimeUtil.getCurrentTime());
		user.setLasttime(1);
		user.setStatus(1);
		
		user.setId(IdUtil.genId());
		
		if(user.getAccount().length() == 0)
		{
			user.setAccount("u" + longToString(user.getId()));
			bmList.add(user.getAccount());
		}
		
		executeInsert("insertUser", user);
		
		for(String bm : bmList)
		{
			int type = 0;
			if(bm.equals(user.getMobile()))
			{
				type = 1;// 手机号
			}
			else if(bm.equals(user.getIdcard()))
			{
				type = 2;
			}
			
			IUserBm o = getUserBm(bm);
			if(o == null)
			{
				o = new IUserBm();
				o.setBm(bm);
				o.setUserid(user.getId());
				o.setType(type);
				executeInsert("insertUserBm", o);
			}
			else
			{
				o.setUserid(user.getId());
				o.setType(type);
				executeUpdate("updateUserBm", o);
			}
		}
		return 1;
	}

	public int delete(long id)
	{
		return executeDelete("delete", id);
	}

	public int updateUser(IUser user)
	{
		return executeUpdate("updateUser", user);
	}
	
	public int updateUserExdata(IUser user)
	{
		return executeUpdate("updateUserExdata", user);
	}

	public int updateUserPassword(long id, String password)
	{
		if(id != 0)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);
			map.put("password", password);
			return executeUpdate("updateUserPassword", map);
		}
		return 0;
	}

	public int updateUserAccount(long userid, String account)
	{
		if(userid > 0)
		{
			String newAccount = account.trim().toLowerCase(Locale.ENGLISH);
			IUser user = getUserById(userid);
			if(user != null)
			{
				String oldAccount = user.getAccount();
				boolean isChangeBm = false;
				IUserBm oldUserBm = getUserBm(oldAccount);
				if(oldUserBm != null && oldUserBm.getUserid() > 0)
				{
					IUserBm newUserBm = getUserBm(newAccount);
					if(newUserBm == null)
					{
						isChangeBm = true;
					}
					else
					{
						if(newUserBm.getUserid() == 0l)
						{
							isChangeBm = true;
						}
					}
				}
				if(isChangeBm)
				{
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", userid);
					map.put("account", account);
					int row = executeUpdate("updateUserAccount", map);
					if(row > 0)
					{
						IUserBm newUserBm = new IUserBm();
						newUserBm.setBm(newAccount);
						newUserBm.setUserid(userid);
						newUserBm.setType(0);
						try
						{
							executeInsert("insertUserBm", newUserBm);
						}
						catch(Exception e)
						{
							executeUpdate("updateUserBm", newUserBm);
						}
						executeDelete("deleteUserBm", oldUserBm);
						return 1;
					}
				}
			}
		}
		return 0;
	}

	public IUser getUserById(long id)
	{
		return (IUser) executeSelect("getUserById", id);
	}

	public IUser getUserByBm(String bm)
	{
		IUserBm o = getUserBm(bm.toLowerCase(Locale.ENGLISH));
		if(o != null && o.getUserid() != 0)
		{
			return getUserById(o.getUserid());
		}
		return null;
	}

	public IUser getUserByOpenid(String openid)
	{
		return (IUser) executeSelect("getUserByOpenid", openid);
	}

	// 用于api
	public List<IUser> queryUserByOrgPid(long orgpid)
	{
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgpid", orgpid);
		return executeSelectList("queryUserByOrgPid", param);
	}

	// 用于api
	public List<IUser> queryUserByOrgId(long orgid)
	{
		return executeSelectList("queryUserByOrgId", orgid);
	}

	static String str = "0123456789abcdefghijklmnopqrstuvwxyz";
	static int strLen = str.length();
	private String longToString(long id)
	{
		java.util.Stack<Integer> s = new java.util.Stack<Integer>();
		long a = id;
		while(a != 0)
		{
			Long b = a % strLen;
			a = a / strLen;
			s.push(b.intValue());
		}
		StringBuilder sb = new StringBuilder();
		while(!s.isEmpty())
		{
			sb.append(str.charAt(s.pop()));
		}
		return sb.toString();
	}
}
